function  [bdraw,m1,CC1,rcoun]  =drawnsta(y,x,prm,prprec,sig,tol,nche);
% function  [bdrawp,m1,CC1,rcoun]=drawnsta(y,x,prm,prprec,sig,tol,nche);
% Draw Coefficients from a Normal Distribution 
% Until a stationary draw is attained 
%
% If do not wish to impose stationarity use drawnres.m 
% 
% Prior ~ Normal( prm, prprec^(-1) )  
%      prprec is the precision  
% y      (Txn) 
% x      (TxK)  
% Prm    (Kx1)  Prior Mean 
% prprec (KxK)  Prior Precision
% Sig    (1x1)
% nche   scalar  which elements should be checked for stationarity 
%
%        e.g if a constant and a trend included and the coefficient vector is 
%        5x1 then nche=3 
%        i.e. assumed autoregressive coefficients given at the end
%
%        b=[deterministic  AR]
% tol    tolerance for uroots level default (if not specified or empty) 
%        is 1e-4
%
% bdraw  (1xK)  Draw from the posterior normal as a row vector 
% m1     (1xK)  Posterior mean 
% CC1    (KxK)  Cholelsky of the posterior variance 
%               V1= CC1'*CC1  
%rejcount     Number of tries needed to obtain a stationary draw 
%
nk=length(prm);

if ( nargin < 7 ) | isempty(nche) == 1; 
    nche=nk; 
    if nargin < 6 ; 
        tol=[]; 
    end
end 

[ty,ny]=size(y); 
[tx,nx]=size(x); 

if tx~=ty
    error('Not equal number of observations in drawcoef'); 
end; 
V1=( prprec+  (1/sig)*(x'*x)  ) \ eye(nk) ; % Posterior Variance  
m1=V1*(prprec*prm + (1/sig)*(x'*y) );        % Posterior Mean  
CC1=chol(V1); 
acc=0;  
rcoun=0; 
while acc < 1;     
    bdraw=m1'+randn(1,nk)*CC1;
    acc=chsta( bdraw(nk-nche+1:end),tol ); 
    rcoun=rcoun+1; 
    if rem(rcoun,500) == 0; 
        warning('500 draws have not yet satisifed the constraint in drawNsta.m') 
    end 
end
rcoun=rcoun-1; 
